require 'tmail'
require 'rexml/document'

$SITE_URL = "http://localhost/cs/"
$ADMIN_USER = "admin"
$ADMIN_PASSWORD = "password"
$ADMIN_EMAIL = "admin@example.org"

def randomChar( len )
  chars = ("a".."z").to_a + ("A".."Z").to_a
  newpass = ""
  1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
  return newpass
end

def startClicker( button , waitTime = 3)
  w = WinClicker.new
  longName = ie.dir.gsub("/" , "\\" )
  shortName = w.getShortFileName(longName)
  c = "start ruby #{shortName}\\watir\\clickJSDialog.rb #{button} #{waitTime} "
  puts "Starting #{c}"
  w.winsystem(c)
  w=nil
end

def build_windows_path(part) 
  build_path(part).gsub(/\//, "\\")
end

def build_path(part) 
  $myDir = Dir.getwd
  "#{$myDir}/#{part}"
end

class Emails
  def isEmailValid?(emailTo, emailType)
    $all_emails = Dir['c:/inetpub/mailroot/queue/*.eml']
    
    $all_emails.each {|x| 
      mail = TMail::Mail.load( x )       

      ## Only look at emails queued in the last 2 minutes
      t = Time.now - 120

      if (mail.date > t && mail.to[0] == emailTo)
        ## Check to make sure that the email does not contain any remaining [] elements
        m = mail.body.scan(/\[\w+?\]/)

        if (m.length == 0)
          ## Get the email body string from template and divide it into an array without the [] elements
          templateBodies = getEmailBody(emailType).split(/\[\w+?\]/)

          ## Check each chunk of text in the body template to make sure it exists in the outgoing email
          templateBodies.each { |b|
            if (mail.body.index(b) == 0)              
              return false
            end
          }
          
          return true
        else
            puts 'Body still contains email template item: ' + m[0]          
        end
      else
        if (mail.date <= t)
          puts 'Email sent too long ago at: ' + mail.date.to_s
        elsif (mail.to[0] != emailTo)
          puts 'Could not find an email in the queue folder with specified email'  
        end
      end
    }
    
    return false
  end
  
  def getEmailBody(emailType)
    if (@emails == nil || @emails.length == 0)
      open('resources/emails.xml') { |f| @emails = f.read  }
    end
    if (@emails.length == 0)
      return ''
    end
    
    doc = REXML::Document.new @emails 
    
    emailBody = REXML::XPath.first(doc, '//email[@emailType="' + emailType + '"]//body')
    emailBody = emailBody.to_s.mgsub([[/.*<body>/i, ''], [/.*<\/body>/i, '']])
    
    return emailBody     
  end
end

class String
  def mgsub(key_value_pairs=[].freeze)
    regexp_fragments = key_value_pairs.collect { |k,v| k }
    gsub(Regexp.union(*regexp_fragments)) do |match|
      key_value_pairs.detect{|k,v| k =~ match}[1]
    end	
  end
end